//
//  StudyDetailVC.m
//  students
//
//  Created by 任辰东 on 2024/2/23.
//

#import "StudyDetailVC.h"
#import "RCDWebView.h"
//#import "StudyApis.h"
#import "NSString+timeStamp.h"
#import "GKPhotoBrowser.h"
//#import "StudyDetailModel.h"

@interface StudyDetailVC ()<GKPhotoBrowserDelegate>
@property (nonatomic, strong) RCDWebView *webView;
@property (nonatomic, strong) NSTimer *countDownTimer;
@property (nonatomic, strong) UIButton *countDownBtn;
@property (nonatomic , strong) StudyModel *model;

@property (nonatomic, assign) long totalTime;
@end

@implementation StudyDetailVC

-(instancetype)initWithModel:(StudyModel *)model
{
    self = [super init];
    if (self) {
        _model = model;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"详情";
    
    [self.webView loadRequestWithRelativeUrl:self.model.content_url];
    
//    WeakSelf
//    [self.webView setImageClicked:^(NSArray *imagesArray, NSInteger index) {
//       StrongSelf
//
//        [self photoBrowsers:imagesArray :index];
//    }];
}

- (void)getData
{
//    NSDictionary *params = @{
//        @"user_id":[GVUserDefaults standardUserDefaults].uid,
//        @"article_id":self.model.article_id
//    };
//    WeakSelf
//    [self showLoadingHUDWithMessage:nil];
//    [StudyApis xxXuexiDetatilRequestWithParams:params SuccessBlock:^(NSNumber *code, NSString *msg, id responseData) {
//        StrongSelf
//        [self hideLoadingHUD];
//        StudyDetailModel *model = [StudyDetailModel mj_objectWithKeyValues:responseData];
//        [self.webView loadURL:[NSURL URLWithString:model.content_url]];
//        if (!self.model.status.boolValue) {
//            self.totalTime = model.study_time.integerValue;
//            [self setupCountDownBtn];
//            self.countDownBtn.hidden = NO;
//            self.countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1
//                                                                  target:self
//                                                                selector:@selector(timeRefresh:)
//                                                                userInfo:nil
//                                                                 repeats:YES];
//            [[NSRunLoop currentRunLoop] addTimer:self.countDownTimer forMode:NSRunLoopCommonModes];
//        }else{
//            self.countDownBtn.hidden = YES;
//        }
//            
//    } FailureBlock:^(NSNumber *code, NSString *msg) {
//        StrongSelf
//        [self showWarningHUDWithMessage:msg completion:NULL];
//    }];
}

- (void)viewWillDisappear:(BOOL)animated {
    
//    [self invalidateTimer];
    [super viewWillDisappear:animated];
}

-(void)invalidateTimer
{
    if(self.countDownTimer)
    {
        [self.countDownTimer invalidate];
        self.countDownTimer = nil;
    }
}

- (void)timeRefresh:(NSTimer *)timer
{
    self.totalTime--;
    [self setupCountDownBtn];
    
    if (self.totalTime<=0) {
        [self invalidateTimer];
        [self endStudy];
    }
}

- (void)endStudy
{
//    NSDictionary *params = @{
//        @"user_id":[GVUserDefaults standardUserDefaults].uid,
//        @"article_id":self.model.article_id
//    };
//    WeakSelf
//    [StudyApis xxStudyAddRequestWithParams:params SuccessBlock:^(NSNumber *code, NSString *msg, id responseData) {
//        StrongSelf
//        self.countDownBtn.hidden = YES;
//        [self showCompletionHUDWithMessage:msg completion:NULL];
//        self.model.status = @"1";
//        if (self.successBlcok) {
//            self.successBlcok(self.model);
//        }
//            
//    } FailureBlock:^(NSNumber *code, NSString *msg) {
//        StrongSelf
//        [self showWarningHUDWithMessage:msg completion:NULL];
//    }];
}

-(void)setupCountDownBtn
{
    if (self.totalTime > 3600) {
        NSString *hour = [NSString stringWithFormat:@"%02ld",self.totalTime/3600];
        NSString *minutes = [NSString stringWithFormat:@"%02ld",(self.totalTime%3600)/60];
        NSString *second = [NSString stringWithFormat:@"%02ld",self.totalTime%60];
        [self.countDownBtn setTitle:[NSString stringWithFormat:@"%@:%@:%@",hour,minutes,second] forState:UIControlStateNormal];
    }else{
        NSString *minutes = [NSString stringWithFormat:@"%02ld",self.totalTime/60];
        NSString *second = [NSString stringWithFormat:@"%02ld",self.totalTime%60];
        [self.countDownBtn setTitle:[NSString stringWithFormat:@"%@:%@",minutes,second] forState:UIControlStateNormal];
    }
}

-(void)photoBrowsers:(NSArray *)imagesArray :(NSInteger)index
{
    NSMutableArray *photos = [@[] mutableCopy];
    [imagesArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        GKPhoto *photo = [[GKPhoto alloc] init];
        photo.url = [NSURL URLWithString:obj];
        [photos addObject:photo];
    }];
    GKPhotoBrowser *browser = [GKPhotoBrowser photoBrowserWithPhotos:photos currentIndex:index];
    browser.showStyle = GKPhotoBrowserShowStyleNone;
    //            browser.loadStyle = GKPhotoBrowserLoadStyleDeterminate;
    browser.delegate = self;
    [browser showFromVC:self];
}

// 长按事件
- (void)photoBrowser:(GKPhotoBrowser *)browser longPressWithIndex:(NSInteger)index
{
    WeakSelf
    GKPhoto * photo = browser.photos[index];
    UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:  UIAlertControllerStyleActionSheet];
    UIAlertAction * save = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        StrongSelf
        [self saveImage:photo.image];
    }];
    
    UIAlertAction * cancleAction = [UIAlertAction actionWithTitle:@"取消" style:    UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVC addAction:save];
    //    [alertVC addAction:share];
    [alertVC addAction:cancleAction];
    [browser presentViewController:alertVC animated:YES completion:nil];
    
}

//-------------- 保存图片回调
- (void)image:(UIImage *)image didFinshedSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    
}

- (void)saveImage:(UIImage *)image
{
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinshedSavingWithError:contextInfo:), (__bridge void *)self);
}

-(void)setupViews
{
    self.webView = [RCDWebView new];
    [self.view addSubview:self.webView];
//    [self.view addSubview:self.countDownBtn];
}

-(void)setupLayout
{
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
//    [self.countDownBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//       
//        make.bottom.equalTo(self.view).offset(kBottomOffset-80);
//        make.right.equalTo(self.view).offset(-30);
//        make.height.width.mas_equalTo(80);
//    }];
//    
//    self.countDownBtn.layer.cornerRadius = 40;
//    self.countDownBtn.layer.masksToBounds = YES;
    
}

-(UIButton *)countDownBtn
{
    if (!_countDownBtn) {
        _countDownBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_countDownBtn setBackgroundColor:[UIColor grayColor]];
        [_countDownBtn setTitle:@"00:00" forState:UIControlStateNormal];
        [_countDownBtn setTitleColor:UIColorFromHex(kColorWhite) forState:UIControlStateNormal];
    }
    return _countDownBtn;
}


@end
